<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>股票指标图表 - </title>
    <uieip type="file" value="inc" src="/yqwin/easyui/include.txt" cache="true" minute="1440"></uieip>
    <uieip type="file" value="css" src="/yqwin/css/yqwin.min"></uieip>
    <uieip type="file" value="js" src="/yqwin/src/yqwin.min"></uieip>
    <script src="/adp/stock/js/highcharts/highstock.js"></script>
    <script src="/adp/stock/js/highcharts/highcharts-more.js"></script>
    <script src="/adp/stock/js/highcharts/modules/exporting.js"></script>
    <script src="/adp/stock/js/highcharts/modules/accessibility.js"></script>
    <script src="/adp/stock/js/pub.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
        }

        #highcharts-chart {
            width: 100%;
            height: 100vh;
        }

        #indicator-controls {
            background: white;
            padding: 3px 0 0 3px;
            background: rgba(255, 255, 255, 0.9);
            padding: 2px 5px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
            z-index: 1000;
        }

        #indicator-controls h3 {
            margin: 0 0 10px 0;
            color: #333;
        }

        #indicator-controls label {
            margin: 0 3px 0 -2px;
            padding: 0;
            cursor: pointer;
        }

        #indicator-controls input[type="text"] {
            padding: 5px;
            margin: 2px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
            width: 26px;
        }

        #indicator-controls>span {
            margin: 0;
        }

        #btn_refresh {
            padding: 4px 8px;
            background-color: #1463da;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        #btn_refresh:hover {
            background-color: #104caa;
            /* 修改悬停颜色 */
        }
    </style>
</head>

<body>
    <div id="indicator-controls">
        <input type='checkbox' id='boll_toggle'> <label for='boll_toggle'>BOLL</label>
        <input type="checkbox" id="ene_toggle"> <label for="ene_toggle">ENE</label>
        <input type="checkbox" id="ma_toggle" checked> <label for="ma_toggle">MA</label>
        <span style="margin-left: 20px;">BOLL：</span>
        <input type="text" id="txt_boll" value="20">
        <span style="margin-left: 20px;">ENE：M1</span>
        <input type="text" id="txt_ene_m1" value="11">
        <span>M2</span>
        <input type="text" id="txt_ene_m2" value="9">
        <span>N</span>
        <input type="text" id="txt_ene_n" value="10">
        <span style="margin-left: 20px;">MA(MACD|VOL)：Period short</span>
        <input type="text" id="txt_ma_short" value="3">
        <span>long</span>
        <input type="text" id="txt_ma_long" value="8">
        <span>signal</span>
        <input type="text" id="txt_ma_signal" value="5">
        <span style="margin-left: 20px;">KDJ：period</span>
        <input type="text" id="txt_kdj_period" value="9">
        <span>kSmooth</span>
        <input type="text" id="txt_kdj_kSmooth" value="3">
        <span>dSmooth</span>
        <input type="text" id="txt_kdj_dSmooth" value="3">
        <button id="btn_refresh">刷新图形</button>

        <input type='checkbox' id='view_vol'> <label for='view_vol'>VOL</label>
        <input type='checkbox' id='view_mdca'> <label for='view_mdca'>MACD</label>
        <input type="checkbox" id="view_kdj"> <label for="view_kdj">KDJ</label>
    </div>
    <div id="highcharts-chart"></div>
    <script>
        var ts_code = stock_pub.urlParams('ts_code') || '600061.SH'; // 若未获取到参数，使用默认值
        console.log('ts_code:', ts_code);
        var svr_response;
        $(function () {
            is_edit(false);
            var tmp = localStorage.getItem('stock_view_params');
            if (tmp) {
                var params = JSON.parse(tmp);
                $("#boll_toggle").prop('checked', params.boll_toggle);
                $("#ene_toggle").prop('checked', params.ene_toggle);
                $("#ma_toggle").prop('checked', params.ma_toggle);
                $("#txt_boll").val(params.txt_boll);
                $("#txt_ene_m1").val(params.txt_ene_m1);
                $("#txt_ene_m2").val(params.txt_ene_m2);
                $("#txt_ene_n").val(params.txt_ene_n);
                $("#txt_ma_short").val(params.txt_ma_short);
                $("#txt_ma_long").val(params.txt_ma_long);
                $("#txt_ma_signal").val(params.txt_ma_signal);
                $("#txt_kdj_period").val(params.txt_kdj_period);
                $("#txt_kdj_kSmooth").val(params.txt_kdj_kSmooth);
                $("#txt_kdj_dSmooth").val(params.txt_kdj_dSmooth);
                $("#view_vol").prop('checked', params.view_vol);
                $("#view_kdj").prop('checked', params.view_kdj);
                $("#view_mdca").prop('checked', params.view_mdca);
            }
            stock_pub.fetchStockData(ts_code, function (response) {
                svr_response = response;
                chart_draw(response);
            });
        });

        // 判断金叉的函数 1-金叉 -1-死叉 0-无
        function checkCrossType(shortLine, longLine, timestamp) {
            index_short = -1;
            index_long = -1;
            for (let i = 0; i < shortLine.length; i++) {
                if (shortLine[i][0] === timestamp) {
                    index_short = i;
                    break;
                }
            }

            for (let i = 0; i < longLine.length; i++) {
                if (longLine[i][0] === timestamp) {
                    index_long = i;
                    break;
                }
            }


            if (index_short < 1 || index_long < 1) {
                return 0; // 数据不足
            }
            if (shortLine[index_short][1] === null || longLine[index_long][1] === null ||
                shortLine[index_short - 1][1] === null || longLine[index_long - 1][1] === null) {
                return 0; // 数据不足
            }

            var cross_type = 0;
            if (shortLine[index_short][1] > longLine[index_long][1] && shortLine[index_short - 1][1] < longLine[index_long - 1][1]) {
                cross_type = checkCrossType(shortLine, longLine, longLine[index_long - 1][0]);
                if (cross_type == 0) {
                    cross_type = 1;
                }
            } else if (shortLine[index_short][1] < longLine[index_long][1] && shortLine[index_short - 1][1] > longLine[index_long - 1][1]) {
                cross_type = checkCrossType(shortLine, longLine, longLine[index_long - 1][0]);
                if (cross_type == 0) {
                    cross_type = -1;
                }
            } else {
                cross_type = 0; // 无
            }

            return cross_type;
        }

        // 在 chart_draw 函数中调用 MACD 计算
        function chart_draw(response) {
            is_edit(false);

            let chart;
            console.log('原始数据:', JSON.stringify(response, null, 4)); // 调试日志

            // 处理新格式的数据
            let data;
            try {
                data = response.rows; // 从新格式中提取rows数据

                if (!Array.isArray(data)) {
                    throw new Error('数据不是数组格式');
                }

                console.log('处理后的K线数据:', data.slice(0, 5)); // 只打印前5条数据用于调试
                console.log('数据长度:', data.length);

                // 验证数据字段
                const firstItem = data[0];
                if (!firstItem || !firstItem.trade_date) {
                    throw new Error('缺少时间字段(trade_date)');
                }
                if (!firstItem.close) {
                    throw new Error('缺少收盘价字段(close)');
                }
            } catch (error) {
                console.error('数据处理错误:', error);
                document.getElementById('highcharts-chart').innerHTML =
                    `<div style="color:red;padding:20px">错误: ${error.message}</div>`;
                return;
            }

            // 严格验证并转换数据格式
            const ohlc = [];
            const volume = [];
            const volume_2 = [];
            const indicators = response.indicators || [];

            // 转换K线数据
            data.forEach((k, index) => {
                if (!k.trade_date || !k.open || !k.high || !k.low || !k.close) return;

                // 修正日期转换逻辑，确保日期正确
                const year = parseInt(k.trade_date.slice(0, 4));
                const month = parseInt(k.trade_date.slice(4, 6)) - 1;
                const day = parseInt(k.trade_date.slice(6, 8));
                if (isNaN(year) || isNaN(month) || isNaN(day)) return;
                const date = new Date(Date.UTC(year, month, day));
                const timestamp = date.getTime();
                if (isNaN(timestamp)) return;

                ohlc.push([
                    timestamp,
                    parseFloat(k.open),
                    parseFloat(k.high),
                    parseFloat(k.low),
                    parseFloat(k.close)
                ]);

                if (k.vol) {
                    // 判断收盘价是否高于开盘价
                    const isUp = parseFloat(k.close) >= parseFloat(k.open);
                    volume.push({
                        x: timestamp,
                        y: parseFloat(k.vol),
                        color: isUp ? '#ff3232' : '#2b908f' // 上涨红色，下跌绿色
                    });

                    volume_2.push([
                        timestamp,
                        parseFloat(k.vol)
                    ]);
                }
            });

            // 1. 计算MA1和MA2 
            const ma_short = document.getElementById('txt_ma_short').value || 3; // 默认为3
            const ma_long = document.getElementById('txt_ma_long').value || 8; // 默认为8
            const ma_signal = document.getElementById('txt_ma_signal').value || 5; // 默认为5 
            const ma_short_Line = calculate.MA(ohlc, parseInt(ma_short), 4);
            const ma_long_Line = calculate.MA(ohlc, parseInt(ma_long), 4);

            const volume_short_Line = calculate.MA(volume_2, parseInt(ma_short), 1);
            const volume_long_Line = calculate.MA(volume_2, parseInt(ma_long), 1);



            // 3. 计算EXPMA(指数平均数)
            // 计算ENE指标 国内:M1 = 11, M2 = 9, N = 10
            /*
               依据：早期国内投资者认为A股的涨跌停幅度为10%，因此将上轨设定为10日均线上浮11%（对应涨停后的价格），
               下轨为下浮9%（对应跌停后的价格）。例如，若10日均线为10元，上轨为10元×1.11=11.1元，下轨为10元×0.91=9.1元
            */
            const ene_m1 = document.getElementById('txt_ene_m1').value || 11; // 默认为11
            const ene_m2 = document.getElementById('txt_ene_m2').value || 9; // 默认为9
            const ene_n = document.getElementById('txt_ene_n').value || 10; // 默认为10
            const ene = calculate.ENE(ohlc, parseInt(ene_m1), parseInt(ene_m2), parseInt(ene_n));

            // 验证并过滤无效数据点
            const validOHLC = ohlc.filter(point =>
                point[0] && point[1] && point[2] && point[3] && point[4]
            );

            // 计算并验证ENE指标
            const validENE = ene.filter(point => point[0] && point[1] && point[2] && point[3]);

            // 计算布林带指标
            const boll_val = document.getElementById('txt_boll').value || 20; // 默认为20
            const boll = calculate.BOLL(ohlc, parseInt(boll_val));
            const validBOLL = boll.filter(point => point[0] && point[1] && point[2] && point[3]);

            // 计算MACD指标
            const macd = calculate.calculateMACD(ohlc, parseInt(ma_short), parseInt(ma_long), parseInt(ma_signal));
            var macd_histogram = [];
            for (let i = 0; i < macd.histogram.length; i++) {
                macd_histogram.push({
                    x: macd.histogram[i][0],
                    y: macd.histogram[i][1],
                    color: macd.histogram[i][1] > 0 ? '#ff3232' : '#2b908f' // 上涨红色，下跌绿色
                });
            }

            //计算金叉死叉
            const plotLines = [];
            for (let i = (macd.signalLine.length - 1); i > 0; i--) {
                var crossType = checkCrossType(macd.macdLine, macd.signalLine, macd.signalLine[i][0]);
                if (crossType == 1) {
                    plotLines.push({
                        color: '#ff3232', // 红色
                        width: 2, // 线宽
                        value: macd.signalLine[i][0], // 交点的y值
                        label: {
                            text: '金叉', // 标签文本
                            align: 'left', // 标签对齐方式
                            verticalAlign: 'middle', // 垂直对齐方式
                            rotation: 0, // 标签旋转角度
                            y: 0 // 标签相对于交点的偏移
                        }
                    })
                } else if (crossType == -1) {
                    plotLines.push({
                        color: '#2b908f', // 红色
                        width: 2, // 线宽
                        value: macd.signalLine[i][0], // 交点的y值
                        label: {
                            text: '死叉', // 标签文本
                            align: 'left', // 标签对齐方式
                            verticalAlign: 'middle', // 垂直对齐方式
                            rotation: 0, // 标签旋转角度
                            y: 0 // 标签相对于交点的偏移
                        }
                    })
                }
            }

            // 计算KDJ指标
            const kdj_period = document.getElementById('txt_kdj_period').value || 9; // 默认为9
            const kdj_kSmooth = document.getElementById('txt_kdj_kSmooth').value || 3; // 默认为3
            const kdj_dSmooth = document.getElementById('txt_kdj_dSmooth').value || 3; // 默认为3
            const kdj = calculate.calculateKDJ(ohlc, parseInt(kdj_period), parseInt(kdj_kSmooth), parseInt(kdj_dSmooth));
            const kLine = kdj.filter(item => item).map(item => [item.x, item.K]);
            const dLine = kdj.filter(item => item).map(item => [item.x, item.D]);
            const jLine = kdj.filter(item => item).map(item => [item.x, item.J]);

            const dg_title = response.name + '(' + response.ts_code + ')';
            var $iframe = $.yqWinPopEdit("iframe");
            if ($iframe.length > 0) {
                $iframe.data("$dg").dialog("setTitle", dg_title);
            }
            $('title').html(dg_title);

            // 创建图表实例时添加 BOLL 系列
            const h_ = window.innerHeight - 45;
            document.getElementById('highcharts-chart').style.height = `${h_}px`;

            var view_vol = document.getElementById('view_vol').checked;
            var view_mdca = document.getElementById('view_mdca').checked;
            var view_kdj = document.getElementById('view_kdj').checked;

            var view_num = 0;
            var chart_height = 0;
            if (view_vol) {
                view_num++;
            }
            if (view_mdca) {
                view_num++;
            }
            if (view_kdj) {
                view_num++;
            }
            if (view_num == 1) {
                chart_height = 40;
            } else if (view_num == 2) {
                chart_height = 30;
            } else if (view_num == 3) {
                chart_height = 20;
            }

            var chart_paras = {
                chart: {
                    type: 'candlestick',
                    zoomType: 'x'
                },
                rangeSelector: {
                    selected: 1,
                    inputEnabled: false
                },
                // title: {
                //     text: response.name + '(' + response.ts_code + ')'
                // },
                series: [{
                    type: 'candlestick',
                    data: ohlc,
                    color: '#2b908f',  // 下跌颜色，绿色
                    lineColor: '#2b908f',  // 下跌边框颜色，与下跌颜色统一
                    upColor: '#ff3232',  // 上涨颜色，红色
                    upLineColor: '#ff3232',  // 上涨边框颜色，与上涨颜色统一
                    dataGrouping: {
                        enabled: false
                    },
                    turboThreshold: 0,
                    id: 'kline'
                }, {
                    type: 'line',
                    name: 'MA short',
                    data: ma_short_Line,
                    color: '#FFA500',  // 颜色：橙色
                    lineWidth: 2,
                    id: 'ma_short'
                }, {
                    type: 'line',
                    name: 'MA long',
                    data: ma_long_Line,
                    color: '#1463da',  // 颜色：蓝色
                    lineWidth: 2,
                    id: 'ma_long'
                }, {
                    type: 'line',
                    name: 'ENE MID',
                    data: validENE.map(point => [point[0], point[1]]),
                    color: '#008000',  // 颜色：深绿色
                    lineWidth: 2,
                    id: 'ENE-MID',
                    dashStyle: 'Dash',
                }, {
                    type: 'line',
                    name: 'ENE UPPER',
                    data: validENE.map(point => [point[0], point[2]]),
                    color: '#FF0000',  // 颜色：红色
                    lineWidth: 2,
                    id: 'ENE-UPPER',
                    dashStyle: 'Dash',
                }, {
                    type: 'line',
                    name: 'ENE LOWER',
                    data: validENE.map(point => [point[0], point[3]]),
                    color: '#0000FF',  // 颜色：蓝色
                    lineWidth: 2,
                    id: 'ENE-LOWER',
                    dashStyle: 'Dash',
                }, {
                    type: 'line',
                    name: 'BOLL MID',
                    data: validBOLL.map(point => [point[0], point[1]]),
                    color: '#000000',  // 颜色：黑色
                    lineWidth: 2,
                    dashStyle: 'Dash',
                    id: 'BOLL-MID'
                }, {
                    type: 'line',
                    name: 'BOLL UPPER',
                    data: validBOLL.map(point => [point[0], point[2]]),
                    color: '#FFA500',  // 颜色：橙色
                    lineWidth: 2,
                    dashStyle: 'Dash',
                    id: 'BOLL-UPPER'
                }, {
                    type: 'line',
                    name: 'BOLL LOWER',
                    data: validBOLL.map(point => [point[0], point[3]]),
                    color: '#00FF00',  // 颜色：绿色
                    lineWidth: 2,
                    dashStyle: 'Dash',
                    id: 'BOLL-LOWER'
                }],
                xAxis: {
                    lineWidth: 2, // 设置 x 轴线条宽度
                    tickWidth: 2, // 设置刻度线宽度
                    plotLines: plotLines
                },
                yAxis: [{
                    labels: {
                        align: 'right',
                        x: -3
                    },
                    title: {
                        text: '价格'
                    },
                    height: (100 - chart_height * view_num) + '%',
                    lineWidth: 2
                }],
                tooltip: {
                    split: true
                },
                navigator: {
                    enabled: true
                },
                scrollbar: {
                    enabled: false
                }
            };

            var yAxis = 0;
            if (view_vol) {
                yAxis++;
                chart_paras.series.push({
                    type: 'column',
                    name: '成交量',
                    data: volume,
                    yAxis: yAxis
                });
                chart_paras.series.push({
                    type: 'line',
                    name: 'short',
                    data: volume_short_Line,
                    color: '#FFA500',  // 颜色：橙色
                    lineWidth: 2,
                    id: 'volume_short',
                    yAxis: yAxis
                });
                chart_paras.series.push({
                    type: 'line',
                    name: 'long',
                    data: volume_long_Line,
                    color: '#1463da',  // 颜色：蓝色
                    lineWidth: 2,
                    id: 'volume_long',
                    yAxis: yAxis
                });

                chart_paras.yAxis.push({
                    labels: {
                        align: 'right',
                        x: -3
                    },
                    title: {
                        text: '成交量'
                    },
                    top: (100 - chart_height * yAxis + 1) + '%',
                    height: (chart_height - 1) + '%',
                    offset: 0,
                    lineWidth: 2,
                    visible: document.getElementById('view_vol').checked
                })
            }
            if (view_mdca) {
                yAxis++;
                chart_paras.series.push(
                    {
                        type: 'line',
                        name: 'MACD Line',
                        data: macd.macdLine,
                        color: '#FFA500',
                        lineWidth: 2,
                        yAxis: yAxis,
                        id: 'MACD-Line',
                    });
                chart_paras.series.push({
                    type: 'line',
                    name: 'Signal Line',
                    data: macd.signalLine,
                    color: '#1463da', //蓝色
                    lineWidth: 2,
                    yAxis: yAxis,
                    id: 'Signal-Line',
                });
                chart_paras.series.push({
                    type: 'column',
                    name: 'Histogram',
                    data: macd_histogram,
                    yAxis: yAxis,
                    id: 'Histogram',
                    pointWidth: 4 // 设置柱状图宽度
                });

                chart_paras.yAxis.push({
                    labels: {
                        align: 'right',
                        x: -3
                    },
                    title: {
                        text: 'MACD'
                    },
                    top: (100 - chart_height * yAxis + 1) + '%',
                    height: (chart_height - 1) + '%',
                    offset: 0,
                    lineWidth: 2,
                    visible: document.getElementById('view_mdca').checked
                });
            }
            if (view_kdj) {
                yAxis++;
                chart_paras.series.push({
                    type: 'line',
                    name: 'KDJ K',
                    data: kLine,
                    color: '#FF0000', // 红色
                    lineWidth: 2,
                    yAxis: yAxis,
                    id: 'KDJ-K'
                });
                chart_paras.series.push({
                    type: 'line',
                    name: 'KDJ D',
                    data: dLine,
                    color: '#00FF00', // 绿色
                    lineWidth: 2,
                    yAxis: yAxis,
                    id: 'KDJ-D'
                });
                chart_paras.series.push({
                    type: 'line',
                    name: 'KDJ J',
                    data: jLine,
                    color: '#0000FF', // 蓝色
                    lineWidth: 2,
                    yAxis: yAxis,
                    id: 'KDJ-J'
                });

                chart_paras.yAxis.push({
                    labels: {
                        align: 'right',
                        x: -3
                    },
                    title: {
                        text: 'KDJ'
                    },
                    top: (100 - chart_height * yAxis + 1) + '%',
                    height: (chart_height - 1) + '%',
                    offset: 0,
                    lineWidth: 2,
                    visible: document.getElementById('view_kdj').checked
                });
            }

            chart = Highcharts.stockChart('highcharts-chart', chart_paras);

            // 绑定切换事件
            function toggleSeries(seriesName, show) {
                console.log(`切换 ${seriesName} 显示状态: ${show}`);
                const series = chart.get(seriesName);
                if (series) {
                    console.log(`找到系列 ${seriesName}`, series);
                    series.setVisible(show, false);
                    chart.redraw();
                } else {
                    console.error(`未找到系列 ${seriesName}`);
                }
            }

            document.getElementById('boll_toggle').addEventListener('change', (e) => {
                console.log('布林带 切换:', e.target.checked);
                toggleSeries('BOLL-MID', e.target.checked);
                toggleSeries('BOLL-UPPER', e.target.checked);
                toggleSeries('BOLL-LOWER', e.target.checked);
            });
            if (!document.getElementById('boll_toggle').checked) {
                toggleSeries('BOLL-MID', false);
                toggleSeries('BOLL-UPPER', false);
                toggleSeries('BOLL-LOWER', false);
            }

            // 绑定切换事件
            document.getElementById('ene_toggle').addEventListener('change', (e) => {
                console.log('ENE 切换:', e.target.checked);
                toggleSeries('ENE-MID', e.target.checked);
                toggleSeries('ENE-UPPER', e.target.checked);
                toggleSeries('ENE-LOWER', e.target.checked);
            });
            if (!document.getElementById('ene_toggle').checked) {
                toggleSeries('ENE-MID', false);
                toggleSeries('ENE-UPPER', false);
                toggleSeries('ENE-LOWER', false);
            }

            document.getElementById('ma_toggle').addEventListener('change', (e) => {
                console.log('ma_short 切换:', e.target.checked);
                toggleSeries('ma_short', e.target.checked);
                toggleSeries('ma_long', e.target.checked);
            });
            if (!document.getElementById('ma_toggle').checked) {
                toggleSeries('ma_short', false);
                toggleSeries('ma_long', false);
            }

            document.getElementById('btn_refresh').addEventListener('click', (e) => {
                refresh();
            });

            // 为复选框添加事件监听器
            document.getElementById('view_vol').addEventListener('change', function () {
                refresh();
            });

            document.getElementById('view_mdca').addEventListener('change', function () {
                refresh();
            });

            document.getElementById('view_kdj').addEventListener('change', function () {
                refresh();
            });

            is_edit(true);
        }

        const checkboxes = ['boll_toggle', 'ene_toggle', 'ma_toggle', 'view_vol', 'view_kdj', 'view_mdca', 'btn_refresh'];
        function is_edit(tf) {
            $("#btn_refresh").prop('disabled', !tf);
            checkboxes.forEach(id => {
                $("#" + id).prop('disabled', !tf);
            });
        }


        function refresh() {
            const saveValues = {
                boll_toggle: $("#boll_toggle").prop('checked'),
                ene_toggle: $("#ene_toggle").prop('checked'),
                ma_toggle: $("#ma_toggle").prop('checked'),
                txt_boll: validateAndSetDefault("#txt_boll", 20),
                txt_ene_m1: validateAndSetDefault("#txt_ene_m1", 11),
                txt_ene_m2: validateAndSetDefault("#txt_ene_m2", 9),
                txt_ene_n: validateAndSetDefault("#txt_ene_n", 10),
                txt_ma_short: validateAndSetDefault("#txt_ma_short", 3),
                txt_ma_long: validateAndSetDefault("#txt_ma_long", 8),
                txt_ma_signal: validateAndSetDefault("#txt_ma_signal", 5),
                txt_kdj_period: validateAndSetDefault("#txt_kdj_period", 9),
                txt_kdj_kSmooth: validateAndSetDefault("#txt_kdj_kSmooth", 3),
                txt_kdj_dSmooth: validateAndSetDefault("#txt_kdj_dSmooth", 3),
                view_vol: $("#view_vol").prop('checked'),
                view_kdj: $("#view_kdj").prop('checked'),
                view_mdca: $("#view_mdca").prop('checked')
            };
            localStorage.setItem('stock_view_params', JSON.stringify(saveValues));

            console.log('刷新');
            // 移除事件
            checkboxes.forEach(id => {
                const checkbox = document.getElementById(id);
                const newCheckbox = checkbox.cloneNode(true);
                checkbox.parentNode.replaceChild(newCheckbox, checkbox);
            });
            chart_draw(svr_response);
        }

        // 提取验证并设置默认值的逻辑到单独的函数
        function validateAndSetDefault(inputId, defaultValue) {
            const val = $(inputId).val();
            if (!validateInput(val)) {
                $(inputId).val(defaultValue);
                return defaultValue;
            }
            return val;
        }
        function validateInput(value) {
            const num = parseInt(value);
            return !isNaN(num) && num > 0;
        }
    </script>
</body>

</html>